<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=100, initial-scale=1.0">
    <title>测试</title>
    
</head>
<body>
    <button onclick="clickme()" class="btn">点击</button>
    <div id="data"></div>
    <script type="text/javascript" >
    function clickme(){
        readbluetooth()
        .then(v => console.log(v))
        .catch(e => console.log(e));
    }
    async function readbluetooth(){
        let device = await navigator.bluetooth.requestDevice({    
            optionalServices: ['00001101-0000-1000-8000-00805f9b34fb']
            , acceptAllDevices: true//设置acceptAllDevices代表查询所有蓝牙设备 也是必须配置optionalServices
        });
        device.addEventListener('gattserverdisconnected', onDisconnected);//监听设备断开连接
        let server = await device.gatt.connect();
        let service = await server.getPrimaryService('00002A35-0000-1000-8000-00805f9b34fb');//这里需要服务UUID 还是可以提供完整的蓝牙UUID或简短的16位或32位形式
        let services = await server.getPrimaryServices();
        let characteristics = await service.getCharacteristics();//获取设备所有信息特征值
        let characteristic = await service.getCharacteristic('00001810-0000-1000-8000-00805f9b34fb');//这里需要读的特征值UUID 还是可以提供完整的蓝牙UUID或简短的16位或32位形式
        characteristic.startNotifications();//开始监听
        characteristic.addEventListener(
            'characteristicvaluechanged', e => {
                //监听设备端的操作 获取到值之后再解析
                console.log('e.target.value:',ab2hex(e.target.value.buffer));
                document.getElementById('data').InnerText=ab2hex(e.target.value.buffer);
            }
        );
 
    }
 
function onDisconnected(event) {
    const device = event.target;
    console.log(`设备: ${device.name} 已经断开连接`);
}
function string2buffer(str) {
    let val = "";
    if (!str) return;
    let length = str.length;
    let index = 0;
    let array = [];
    while (index < length) {
        array.push(str.substring(index, index + 2));
        index = index + 2;
    }
    val = array.join(",");
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16);
    })).buffer
}
function ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2);
        }
    )
    return hexArr.join('');
}    </script>
</body>
</html>